import { createRouter, createWebHistory } from "vue-router";
import { userStore } from '@/stores/userStore';

const routes = [
  {
    path: "/",
    name: "Index",
    title: '首页',
    component: () => import("@/views/index/index.vue"),
  },
  {
    path: "/login",
    name: "Login",
    title: '登录',
    component: () => import("@/views/login/index.vue"),
  },
  {
    path: "/reg",
    name: "Reg",
    title: '注册',
    component: () => import("@/views/reg/index.vue"),
  },
  {
    path: "/mall",
    name: "Mall",
    title: '商城',
    component: () => import("@/views/mall/index.vue"),
  },
  {
    path: "/person",
    name: "Person",
    title: '个人中心',
    component: () => import("@/views/person/index.vue"), 
    meta: { requiresAuth: true }, 
  },
  {
    path: "/user",
    name: "User",
    title: '我的信息',
    component: () => import("@/views/user/user.vue"), 
  },
  {
    path: '/404',
    component: () => import("@/views/notfound/NotFound.vue"),
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404' 
  },
  {
    path: "/article",
    name: "Article",
    title: '文章',
    component: () => import("@/views/article/index.vue"), 
  },
  {
    path: "/person/list",
    name: "Personlist",
    title: '个人列表',
    component: () => import("@/views/person/List.vue"), 
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.addRoute({
  path: '/person/:id',
  component: () => import("@/views/person/Detail.vue"), 
})

router.addRoute({
  path: '/article/:id',
  component: () => import("@/views/article/Detail.vue"), 
})

router.beforeEach((to, from, next) => {
  const store = userStore();
  if (to.meta.requiresAuth && !store.isLoggedIn) {
    next('/login');
  } 
  else if (to.path === '/login' && store.isLoggedIn) {
    next('/person'); 
  }
  else {
    next();
  }
});

export default router;